package com.gzw.shop.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.gzw.shop.App;
import com.gzw.shop.activity.LoginActivity;
import com.gzw.shop.bean.User;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by JACKYGUO on 2017-05-05.
 */

public abstract class BaseFragment extends Fragment {

    private Unbinder unbinder;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(getLayoutId(), container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initData();
        return view;
    }

    public abstract int getLayoutId();

    public abstract void initView();

    public abstract void initData();

    /**
     * 用于验证是否要登录的方法
     *
     * @param intent      意图，需要跳转到某个页面
     * @param isNeedLogin 是否需要登录
     */
    public void startActivity(Intent intent, boolean isNeedLogin) {

        //如果需要登录
        if (isNeedLogin) {
            User user = App.getInstance().getUser();
            if (user != null) {
                //用户已经登录过，直接跳转
                super.startActivity(intent);
            } else {
                //用户没登录过，跳转登录界面
                App.getInstance().setIntent(intent);
                Intent intent1 = new Intent(getActivity(), LoginActivity.class);
                super.startActivity(intent1);
            }
        } else {
            //如果不需要登陆，直接跳转1
            super.startActivity(intent);
        }
    }

    /**
     * 用于验证是否要登录的方法
     *
     * @param intent      意图，需要跳转到某个页面
     * @param isNeedLogin 是否需要登录
     */
    public void startActivityForResult(Intent intent, int requestCode, boolean isNeedLogin) {

        //如果需要登录
        if (isNeedLogin) {
            User user = App.getInstance().getUser();
            if (user != null) {
                //用户已经登录过，直接跳转
                super.startActivityForResult(intent, requestCode);
            } else {
                //用户没登录过，跳转登录界面
                App.getInstance().setIntent(intent);
                Intent intent1 = new Intent(getActivity(), LoginActivity.class);
                super.startActivityForResult(intent1, requestCode);
            }
        } else {
            //如果不需要登陆，直接跳转1
            super.startActivityForResult(intent, requestCode);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
